package objReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;

public class MaterialReader 
{
	static ArrayList<Material> materials = null;
	static int materialCount;
	static BufferedReader br;
	static Scanner lineTokenizer;
	
	public static ArrayList<Material> readMaterialFile(String filename/*, objModel model*/)
	{
		/* Initialize materials array */
		materials = new ArrayList<Material>();
		materialCount = -1;
		String thisLine = "";
		String newTexture;
		
		/* Initialize i/o data structures */
		try
		{
			br = new BufferedReader(new FileReader(filename));
			
			/* Read and parse the file */
			while((thisLine = br.readLine()) != null)
			{
				lineTokenizer = new Scanner(thisLine);
				
				if(thisLine.startsWith("newmtl ")) /* New material */
				{
					materialCount++;
					
					lineTokenizer.next(); /* Skip the 1st string */
					materials.add(new Material(lineTokenizer.next()));
				}
				else if(thisLine.startsWith("Kd ")) /* ambient color */
				{
					lineTokenizer.next();
					
					/* Get the RGB values */
					materials.get(materialCount).setColor(lineTokenizer.nextFloat(),
														  lineTokenizer.nextFloat(),
														  lineTokenizer.nextFloat(),
														  1.0f);
				}
				else if(thisLine.startsWith("map_Kd "))
				{
					newTexture = thisLine.substring(thisLine.indexOf(" ") + 1, thisLine.length()); /* Parse texture name */
					//model.setTexture(loadTextureFromFile(newTexture)); /* Add texture to array */
					materials.get(materialCount).setTexture(loadTextureFromFile(newTexture));
				}
			}
		}
		catch(FileNotFoundException e)
		{
			System.err.println("Error reading materials file. " + e.toString());
			System.exit(0);
		}
		catch(Exception e)
		{
			System.err.println("General error while parsing material data. line = '" + thisLine + "'" + e.toString());
		}

		/* After file is read, close the filereaders */
		try
		{
			br.close();
		}
		catch(Exception e)
		{
			System.err.println("Error closing file. " + e.toString());
			System.exit(0);
		}
		
		/* Return the materials array */
		return materials;
	}
	
	/* Returns NULL if texture is either not supported or Exception is found. */
	public static Texture loadTextureFromFile(String filename)
	{
		Texture texture = null;
		String type = "";
		
		if(filename.toLowerCase().endsWith("jpg"))
			type = "JPG";
		else if(filename.toLowerCase().endsWith("png"))
			type = "PNG";
		else if(filename.toLowerCase().endsWith("bmp"))
			type = "BMP";
		else
		{
			System.err.println(filename + " is not a supported texture type. Supported types are JPG, PNG, BMP.");
		}
		
		if(!type.isEmpty())
		{
			System.out.println("Loading texture from file '" + filename + "'...");		
			try
			{
				texture = TextureLoader.getTexture(type, new FileInputStream(new File(filename)), true, GL11.GL_LINEAR);
			}
			catch(Exception e)
			{
				System.err.println("Error loading texture: " + e.toString());
				System.exit(0);
			}
		}
		
		return texture;
	}
	
	public static int getIndexOfMaterialWithName(String name, ArrayList<Material> arr)
	{
		for(int index = 0; index < arr.size(); index++)
		{
			if(arr.get(index).getName().equalsIgnoreCase(name))
				return index;
		}
		
		return -1;
	}
}
